/**
 * 认证相关工具函数
 */

/**
 * 从localStorage获取用户认证信息
 */
export const getAuthInfo = () => {
  try {
    const userInfo = localStorage.getItem("userInfo");
    const token = localStorage.getItem("token");

    if (!userInfo || !token) {
      return null;
    }

    const userInfoObj = JSON.parse(userInfo);
    const jwtToken = userInfoObj?.token;

    if (!jwtToken) {
      return null;
    }

    return {
      userInfo: userInfoObj,
      token,
      jwtToken,
    };
  } catch (error) {
    console.error("获取认证信息失败:", error);
    return null;
  }
};

/**
 * 检查用户是否已登录
 */
export const isLoggedIn = (): boolean => {
  return getAuthInfo() !== null;
};

/**
 * 获取带认证头部的fetch配置
 */
export const getAuthHeaders = () => {
  const authInfo = getAuthInfo();

  if (!authInfo) {
    throw new Error("用户未登录");
  }

  return {
    "Content-Type": "application/json",
    custom: authInfo.jwtToken,
  };
};

/**
 * 带认证的fetch请求
 */
export const authFetch = async (url: string, options: RequestInit = {}) => {
  const authInfo = getAuthInfo();

  if (!authInfo) {
    throw new Error("用户未登录");
  }

  const defaultOptions: RequestInit = {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      custom: authInfo.jwtToken,
    },
  };

  const mergedOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers,
    },
  };

  return fetch(url, mergedOptions);
};
